<?php 

/**
 * 店铺角色管理
 * @Author      jiating
 * @DateTime    2018-04-11
 */

namespace app\admin\controller;

use think\Db;

class Role extends Base{

	public function index() {

		$modules = Db::table('module')->select();
		$mMap = [];
		foreach ($modules as $v) {
			// $mMap[$v['id']] = $v;
			$mMap[$v['pId']][] = $v['pId'] != 0 ? $v : [];
		}
		foreach ($modules as $mk => $mv) {
			if($mv['pId'] == 0) {
				// dump($mMap[$mv['id']]);die;
				$modules[$mk]['child'] = isset($mMap[$mv['id']]) ? $mMap[$mv['id']] : []; 
			} else {
				unset($modules[$mk]);
			}
		}
		// dump($modules);  //组装好的菜单数组

		$list = Db::table('role')->where(['tenantId'=>session('TENANT_ID')])->order("updateDate DESC")->select();
		$this->assign('list',$list);
		return $this->fetch();
	}

	public function add() {
		dump(session('member'));
		$list = Db::table('module')->where(['isRoleSet'=>1])->select();
		$this->assign('list',$list);
		return $this->fetch();
	}

	public function addPost() {
		$member = session('member');
        $data = [
        	'name' => $_POST['name'],
        	'moduleIds' => implode(',', $_POST['moduleIds']),
        	'createDate' => time(),
        	'updateDate' => time(),
        	'createOper' => $member['id'],
        	'updateOper' => $member['id'],
        	'roleId' => $post['roleId'],
        	'tenantId' => $member['tenantId']
        ];
        $add = Db::table('role')->insert($data);
        if($add) {
        	return $this->redirect('index');
        } else {
        	return $this->error('网络出错，请重试');
        }
	}

	public function edit() {
		$role_id = $this->request->param('role_id');
		$role = Db::table('role')->where(['role_id'=>$role_id])->find();

		if($role['tenantId'] != session('TENANT_ID')) {  //验证所修改的是否为本店铺的角色
			return $this->error('只能修改本店铺的角色！');
		}

		$list = Db::table('module')->where(['isRoleSet'=>1])->select();
		$this->assign('list',$list);
		$this->assign('role',$role);
		return $this->fetch();
	}


	public function editPost() {
		$data = [
        	'name' => input('post.name'),
        	'moduleIds' => implode(',', $_POST['moduleIds']),
        	'updateDate' => time(),
        	'updateOper' => session('TENANT_ID')
        ];

        $save = Db::table('role')->where(['role_id'=>input('post.role_id')])->update($data);
        if($save) {
        	return $this->success('修改成功','index','',2);
        }
	}


	public function delete() {
		$role_id = $this->request->param('role_id');

        $where = ['role_id'=>$role_id,'tenantId'=>session('TENANT_ID')];

        if(Db::table('role')->delete($where)) {
        	return $this->success('删除成功','index','',2);
        } else {
        	return $this->error('网络出错，请重试');
        }
	}




}